/*
 * @Author: zhangxiao
 * @Email: zhangxiao0125@163.com
 * @Date: 2020-06-09 13:24:27
 * @Last Modified by: zhangxiao
 * @Last Modified time: 2020-08-31 13:41:28
 * @Description: 公共搜索页面
 */

import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_main_tabbar.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/search/data.dart';
import 'package:flutter_code_framework/model_data/search/listviewModel.dart';
import 'package:flutter_code_framework/model_data/search/search.dart';
import 'package:flutter_code_framework/pages/class/class_info_page.dart';
import 'package:flutter_code_framework/pages/common/resources_webview.dart';
import 'package:flutter_code_framework/pages/common/voice_player.dart';
import 'package:flutter_code_framework/pages/lesson_publish.dart';
import 'package:flutter_code_framework/route/route_transition.dart';

import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/widgets/video_player.dart';
import 'package:flutter_code_framework/widgets/x_video_player.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';

class Search extends BaseWidget {
  String resourceType;
  String title;
  bool flag;
  Search({Key key,this.resourceType,this.title,this.flag=false}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _SearchState();
  }
}

class _SearchState extends BaseWidgetState<Search> {
ScrollController _controller = new ScrollController();
TextEditingController _title = TextEditingController(); 

Data _items=new Data(); 
List<SearchData>list=[];
int _pageCount=1;     //总页码
String dataId='';
String classType='';
String _txtTitle='';  //搜索框内容
String _emptyWidgetContent='';

  @override
  Widget buildWidget(BuildContext context) {
    return WillPopScope(child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
          Container(
            height: 58.0,
            width: MediaQuery.of(context).size.width,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              textDirection: TextDirection.rtl,
              children: <Widget>[
                 Container(
                    width:32,
                    margin: EdgeInsets.only(right:24.0),
                    child:GestureDetector(
                      child:Text('取消',style:TextStyle(fontSize: 14.0,color: Theme.of(context).primaryTextTheme.caption.color)),
                      onTap: ()=>RouteTransition(BaseMainTabbarPage()).pushAndRemoveUntilTransRoute(context))
                 ),
              
                 Expanded(
                  child:Container(
                    height: 30,
                     padding: EdgeInsets.only(left:24.0,right: 18),
                     child:TextFormField(
                      controller:_title ,
                      decoration:InputDecoration(
                        prefixIcon:Icon(SFSymbols.search,size: 14,color:Theme.of(context).cursorColor),
                        contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
                                      border: OutlineInputBorder(
                                              borderRadius: BorderRadius.circular(146.0),
                                              borderSide: BorderSide.none
                                            ),
                                            filled: true,
                                            fillColor: Theme.of(context).textSelectionColor
                       
                      ),
                      textInputAction: TextInputAction.search, 
                      onFieldSubmitted: (value){
                        if(list.length>0){
                          list.clear();
                        }
                        _getSearch(isAll:true);
                      },
                   )
                  )
                 )
                ],
            )),
          Expanded(
               child: list.length==0?Container(child:Text('$_emptyWidgetContent'),alignment: Alignment.center): RefreshIndicator(
                child: ListView.builder(
                controller: _controller,
                physics: BouncingScrollPhysics(),
                itemCount:list.length+1,
                scrollDirection: Axis.vertical,
                itemBuilder: (BuildContext context,int index){
                if(index<list.length){
                listviewModel _model= _bindLevelTitle(list[index]);
                return Container(
                  height: 100,
                  child: ListTile(
                  title:Container(
                    margin: EdgeInsets.only(top:20.0),
                    child:Row(
                    children: <Widget>[
                      Flexible(
                        child:Container(
                          margin: EdgeInsets.only(left:12.0,bottom:10),
                          child:Text('${list!=null?list[index].title:""}',maxLines:1,overflow: TextOverflow.ellipsis, style:TextStyle(fontSize: 18.0,color: Theme.of(context).primaryTextTheme.caption.color)),
                      )),
                      Container(
                      margin: EdgeInsets.only(left:6.0,bottom: 10),
                              child: list!=null?  Icon(_model.icoData,size:21,color:Color.fromRGBO(57,135,110,1)):null,
                              )  
                      ],
                  ))  ,
                subtitle: Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   children:  <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children:<Widget>[
                          Container(
                            margin:EdgeInsets.only(left:12.0,bottom: 10.0),
                            child: Text(_model.levelTitle,style:TextStyle(color:Theme.of(context).primaryTextTheme.caption.color,fontSize: 14.0)),
                          ),
                          Align(
                            alignment: Alignment.centerRight,
                          ),
                           _model.buttonTitle.isNotEmpty?(
                            Container(
                               margin: EdgeInsets.only(right: 14.0,bottom:10.0),
                               child:SizedBox(
                                  height: 24.5,
                                  width: 80,
                                  child:RaisedButton(
                                  color: Colors.transparent,
                                  elevation: 0,
                                  splashColor: Colors.transparent,
                                  highlightColor: Colors.transparent,
                                  shape: RoundedRectangleBorder(
                                   side: BorderSide(color:Theme.of(context).primaryTextTheme.headline6.color),
                                  borderRadius: BorderRadius.all(Radius.circular(145.0))
                                 ),
                                 child: Text(_model.buttonTitle,style: TextStyle(fontSize: 12, color:Theme.of(context).primaryTextTheme.headline6.color)),
                                 onPressed:()=>_classOperation(list[index])
                              )
                            )
                          )
                         ):Container(margin: EdgeInsets.only(bottom:10.0))
                        ]),
                        list!=null?Container(
                            padding: EdgeInsets.only(top:12,right:14,left:12.0),
                            child:Divider(
                              height:1,
                              color: Theme.of(context).primaryTextTheme.caption.color,
                            )
                        ):Container()
                  ]
                ),onTap:()=>_resourceDetailed(list[index]) ,
              )
            );
           }else{
             if(1<_pageCount){
               return Container(
                padding: EdgeInsets.all(16.0),
                alignment: Alignment.center,
                child: SizedBox(
                  width: 24.0,
                  height: 24.0,
                  child: CircularProgressIndicator(strokeWidth: 2.0,),
                ),
                );
             }else{
                  if(_pageCount>1){
                    return Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(16.0),
                        child: Text("----我是有底线的-----", style: TextStyle(color: Colors.grey)
                      ));
                  }
             }
            }
           },
        ),
        onRefresh:_handleRefresh,
        ),
        )
      ],
    // ignore: missing_return
    ),onWillPop:(){
       RouteTransition(BaseMainTabbarPage()).pushAndRemoveUntilTransRoute(context);
       }
    );
  }
  @override
  void initState() {
    super.initState();
    if(list.length>0){
        list.clear();
    } 
  
      if(widget.flag){
        _getSearch(isAll: true);
      }else{
       _getSearch(isAll: false);
      }
      
    
      
      //监听上拉加载数据
      _controller.addListener((){
        if(_controller.position.pixels == _controller.position.maxScrollExtent){
          if(1<_pageCount){
              _loadMore();
          }
        }
    });

    _title.addListener((){
         _txtTitle=_title.text;
    });

    if(widget.title!=null){
     _title.value=_title.value.copyWith(text:widget.title);
    }
  }

  @override
   void dispose() {
    super.dispose();
     _controller.dispose();
  }

  @override
  void onCreate() {
     setLoadingWidgetVisible(true);
  }

  @override
  void onPause() {

  }

  @override
  void onResume() {

  }


 // 下拉刷新方法
  Future<Null> _handleRefresh() async {
     await Future.delayed(Duration(seconds: 1), () {
      var _firstTime=list.first.createTime;
      if(mounted)
        setState(() {
          _getSearch(isAll:true,selecttime:_firstTime,bottom:false);
        });
     });
  }

  // 上拉加载
  Future<Null> _loadMore() async {
      var  _lastTime=list.last.createTime;
      await Future.delayed(Duration(seconds: 2), () {
        if(mounted)
          setState(() {
              _getSearch(isAll: true, selecttime: _lastTime.toString());
          });
    });
  }
  
  //班级按钮操作
  _classOperation(SearchData data){
    switch(data.type){
        case "教学班":
        case "行政班":
            if(data.isManageTeacher==1){
              dataId=data.id;
              classType='解散';
               G.showToastDialog(context,
                      "确定要解散此班级吗",
                      title: "提示", callBack: clickDialogOk);
              // RouteTransition(XDialogPage(
              //         '确定要解散此班级吗',
              //         callBack: () {
              //          dissolve(data.id);
              //         },
              //       )).pushTransRoute(context);
          }else{
              if(data.isJoinClass==1){
                dataId=data.id;
                classType='退出';
                 G.showToastDialog(context,
                      "确定要退出此班级吗",
                      title: "提示", callBack:clickDialogOk);
                //  RouteTransition(XDialogPage(
                //       '确定要退出此班级吗',
                //         callBack: () {
                //            exit(data.id);
                //         },
                //     )).pushTransRoute(context);
              }else{
               apply(data.id);
              }    
          }
          break;
      }
  }
  Function clickDialogOk(){
    if(classType=='退出'){
      exit(dataId);
    }else{
      dissolve(dataId);
    }
  
  }
  //解散班级
  dissolve(classId) async {
    var rs =await G.req.classData.dissolve(classId:classId,operation: 'dissolve');
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast('解散成功');
      //关闭当前页跳转到列表页
      Navigator.pushAndRemoveUntil(
        context, new MaterialPageRoute(builder: (context) => new Search(title: _title.text, resourceType: widget.resourceType,flag: true,)),
        (route) => route == null,
      );
    }
  }
  
  //退出班级
  exit(classId) async {
      var rs =await G.req.classData.exit(classId:classId,operation: 'exit');
      if (rs.data['isOk'] == true) {
        //弹出'退出成功'，当前页面关闭
        showNormalToast('退出成功');
        //关闭当前页跳转到列表页面
      Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new Search(title: _title.text, resourceType: widget.resourceType,flag: true,)),
              (route) => route == null,
        );
      }
    }

   //加入班级
  apply(classId)async{
      var rs =await G.req.classData.apply(classId:classId);
      if (rs.data['isOk'] == true) {
        showNormalToast('加入成功');
        //关闭当前页跳转到列表页
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new Search(title: _title.text, resourceType: widget.resourceType,flag:true)),
          (route) => route == null,
        );
       
      }else{
        
        showRightToast(rs.data['errMsg']);
      }
  }
  
   //搜索，默认是全部类型，
  void _getSearch({bool isAll=false, String selecttime='',bool bottom=true}) async{
    int _totalCount=0;
   
    if(isAll==false){
         list.addAll(List<SearchData>());
         setLoadingWidgetVisible(false);
         setState(() {
           
         });
      return;
   }
    var rs= await G.req.search.search(title:_txtTitle, type:widget.resourceType, schoolId:G.user.data.schoolId,pageSize:pageNum,bottom: bottom,selecttime:selecttime);
     _items=Data.fromJson(rs.data);
  
     if(_items.data!=null){
        //判断上拉/下拉刷新 
       if(!bottom){
         //下拉数据刷新，不更新总页码数
         list.insertAll(0,_items.data);
       }else{
         list.addAll(_items.data);
         if(_items.data.length>0){
           _totalCount=_items.data[0].totalCount;
         }
         if(_totalCount>pageNum){
          var mPageCount=(_totalCount + pageNum - 1)/pageNum;
          _pageCount=mPageCount.toInt();
         }else{
            _pageCount=1;
          }
       }
     }else{
       _emptyWidgetContent=_title==null?" ":'暂无数据~';
     }
     setLoadingWidgetVisible(false);
     if(mounted)
        setState(() {});
  }
  
  // list 二级标题名称
  listviewModel _bindLevelTitle(SearchData data){
    listviewModel model=new listviewModel();
    switch(data.type){
      case "备课":
          model.levelTitle="发布人:${data.createMan}";
          break;
      case "视频":
          model.levelTitle="${data.duration}  (${data.rcName})";
          model.icoData=SFSymbols.play_rectangle_fill;
          break;
      case "音频":
          model.levelTitle="文件大小:${data.duration}  (${data.rcName})";
          model.icoData=Icons.audiotrack;
          break;
      case "行政班":
      case "教学班":
           model.levelTitle="${data.type}";
        if(data.isManageTeacher==1){
            model.buttonTitle="解散班级";
        }else{
          if(data.isJoinClass==1){
              model.buttonTitle="退出班级";
          }else{
              model.buttonTitle="加入班级";
          }    
        }
        break;
      case "PPT":
      case "Word":
      case "Excel":
      case "PDF":
         model.icoData=SFSymbols.doc_fill;
         model.levelTitle="文件大小:${data.duration}  (${data.rcName})";
        break;
      case "Html":
        model.icoData=SFSymbols.compass_fill;
        model.levelTitle="在线多媒体页面";
       break;
      } 
     
      return model;
  }
  
  // 行数据绑定跳转
  _resourceDetailed(SearchData data){
     switch(data.type){
      case "视频":
          List<VideoType>listVideoType=new List();
          if(data.resourcesurlsuper.isNotEmpty){
            listVideoType.add(VideoType(name: '超清', url:data.resourcesurlsuper));
          } 
          if(data.resourcesurlhigh.isNotEmpty)
          {
            listVideoType.add(VideoType(name: '高清', url:data.resourcesurlhigh));
          }
          if(data.resourcesurllow.isNotEmpty){
            listVideoType.add(VideoType(name: '标清', url:data.resourcesurllow));
          }
          RouteTransition(VideoPlayer(path: [PlayerInputInstance(title: data.title,list:listVideoType)], sourceType: 'network')).pushTransRoute(context);                       
        break;
      case "音频":
           RouteTransition(VoicePlayer(url:data.resourcesurllow,title:data.title)).pushTransRoute(context);
       break;
      case "PPT":
      case "Word":
      case "Excel":
      case "PDF":
      case "Html":
          RouteTransition(ResourcesWebview(resourceUrl: data.resourcesurllow,title: data.title)).pushTransRoute(context);
       break;
      case "行政班":
      case "教学班":
          RouteTransition(ClassInfoPage(classId: data.id)).pushTransRoute(context);
        break;
      case "备课":
        var _moduleTypeMap={'小作业模块':'小作业','文本图片模块':'图文','微课模块':'视频','音频模块':'音频'};
        RouteTransition(LessonPublish(id:data.id,lessonType:_moduleTypeMap[data.moduleType])).pushTransRoute(context);
         break;
    }
  }
 }
